package com.glamour.hlcity.module.url.analysis.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.glamour.hlcity.common.data.model.UrlNode;
import com.glamour.hlcity.common.model.Node;
import com.glamour.hlcity.common.util.ListUtil;
import com.glamour.hlcity.common.util.StringUtil;
import com.glamour.hlcity.module.url.analysis.UrlAnalysis;

public class UrlAnalysisImpl implements UrlAnalysis {
	private final static String TOP_URL_NO="HTML_HREF_TOP";
	private final static Integer ZERO=0;
	private final static Integer LEVEL_ONE=1;
	

	@Override
	public UrlNode analysisUrl(String url) {
		if(StringUtils.isBlank(url)){
			return null;
		}
		List<String> urlPartList=StringUtil.split(url, StringUtil.SPLIT_X);
		UrlNode urlNode=execute(TOP_URL_NO);
		urlNode.setLevel(LEVEL_ONE);
		recursive(urlNode, urlPartList, ZERO);
		return urlNode;
	}
	
	/**
	 * 构建节点
	 * @param urlPart
	 * @return
	 */
	private UrlNode execute(String urlPart){
		UrlNode urlNode=new UrlNode();
		urlNode.setNodeName(urlPart);
		urlNode.setNodeNo(urlPart);
		urlNode.setNodeType(Node.LINK_NODE_TYPE_HREF_PART_TEXT);
		urlNode.setText(urlPart);
		return urlNode;
	}
	
	/**
	 * 递归构建url tree 结构
	 * @param parentUrlNode
	 * @param urlPartList
	 * @param i
	 */
	private void recursive(UrlNode parentUrlNode,List<String> urlPartList,int i){
		if(parentUrlNode==null){
			return;
		}
		if(urlPartList.size()<=i){
			return;
		}
		//设置新节点
		UrlNode urlNode=execute(urlPartList.get(i));
		urlNode.setLevel(parentUrlNode.getLevel()+1);
		urlNode.setParentNode(parentUrlNode);
		urlNode.setParentNodeNo(parentUrlNode.getNodeNo());
		if(i==urlPartList.size()-1){
			urlNode.setLeaf(true);
		}
		//i递增
		i++;
		//父亲节点新增子节点
		parentUrlNode.addChildNode(urlNode);
		recursive(urlNode, urlPartList, i);	
	}
	

	@Override
	public void overlapNode(UrlNode mNode, UrlNode cNode) {
		recursiveOverlap(mNode, cNode);
		return;
	}
	
	private void recursiveOverlap(Node mNode,Node partNode){
		if(mNode==null || partNode==null){
			return;
		}
		//如果主干树节点递归结束将需要重叠的子树挂载到主干树上
		if(mNode.getChildNodes().isEmpty()){
			Node cTemp=ListUtil.first(partNode.getChildNodes());
			if(cTemp==null){
				return;
			}
			mNode.addChildNode(cTemp);
			cTemp.setParentNode(mNode);
			cTemp.setParentNodeNo(mNode.getNodeNo());
		}else{
			//将子树以重叠规则挂载到主干树上
			Node cTemp=ListUtil.first(partNode.getChildNodes());
			if(cTemp==null){
				return;
			}
			Node mTempTaget=null;
			for(Node mTemp:mNode.getChildNodes()){
				if(cTemp.getNodeNo().equals(mTemp.getNodeNo())){
					mTempTaget=mTemp;
					break;
				}
			}
			//如果没有相同的，则在该目录下挂载子树
			if(mTempTaget==null){
				mNode.addChildNode(cTemp);
				cTemp.setParentNode(mNode);
				cTemp.setParentNodeNo(mNode.getNodeNo());
			}else{
				recursiveOverlap( mTempTaget,cTemp);
			}
		}
		
	}
}
